<template>
  <div class="box" v-if="emailList.length">
    <div class="title">
      {{ emailList[0].subject }}
    </div>
    <div class="scroll_view" ref="boxRef">
      <div style="margin-bottom: 20px;" v-for="(item, index) in emailList" :key="index">
        <EmailCon ref="emailConRef" @setReadStatus="setReadStatus" :index="index" @onScrollTo="handlerToFile" @onClick="handleClick" :email="item" :observer="true"/>
      </div>
    </div>
    <div v-if="pagination.total > pagination.pageSize" class="page">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        small background layout="prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </div>
    <BackToTop />
  </div>
  <div v-else class="box center">
    <div class="empty"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineEmits, nextTick } from 'vue';
import { storeToRefs } from 'pinia';

import api from "/@/api/email/index";
import { useEmail } from '/@/stores/email';
import { getEmailName } from '/@/utils/index';
import pinia from '/@/stores/index';
import BackToTop from "/@/components/BackToTop.vue";
import EmailCon from './emailCon.vue';


const stores = useEmail(pinia);
const { currentId } = storeToRefs(stores);

const otherEmail = ref<any>([]);
const emailList = ref<any>([]);
const detail = ref<any>(null);
const boxRef = ref();
const emailConRef = ref();
const userBGColor = ref('');
const messageId = ref('');
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

const emit = defineEmits(['onClick', 'getDetailFinished']);

const handleClick = (emial: any, action: string) => emit( 'onClick', action, emial);

const setReadStatus = (email: any) => {
  emailList.value.find((item: any) => item.id === email.id).isSeen = true;
}
const getEmailDetail = async() => {
  api.email.getDetail(currentId.value, {
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
  }).then((res: any) => {
    console.log('res', res)
    const dataList = res.data;
    const list = dataList && dataList.length ? dataList : [res.data.emailInfo];
    const newList = list.map((item: any) => adapt(item));
    emailList.value = []; // 清空列表，避免追加
    newList.forEach((item: any, index:number) => {
      item.color = userBGColor.value;
      if(index === 0 && !item.isSeen) {
        item.isSeen = true;
      }
      emailList.value.push(item)
    })
    pagination.value.total = res.total || 0
  })
};

const handleCurrentChange = (pageNum: number) => {
  pagination.value.pageNum = pageNum;
  getEmailDetail();
  handlerToFile(0)
};

const adapt = (email: any) => {
  const ccEmailList = email.ccEmail ? email.ccEmail.split(',') : [];
  const toEmailName = email.toEmailName ?  email.toEmailName : getEmailName(email.toEmail);
  const fromEmailName = email.fromEmailName ? email.fromEmailName : getEmailName(email.fromEmailName);
  const ccEmail = ccEmailList.map((item: string) => adapt2(item));
  return {
    ...email,
    toEmailName,
    fromEmailName,
    ccEmail
  };
};

const setUserBG = (messageIdVal:string, colorVal:string) => {
  messageId.value = messageIdVal
  userBGColor.value = colorVal
}

const adapt2 = (ccEmail: string) => {
  if (ccEmail.includes(' ')) {
    const list = ccEmail.split(' ');
    return {
      name: list[0],
      email: list[1],
    }
  }
  
  return {
    name: getEmailName(ccEmail),
    email: ccEmail,
  }
}

const handlerToFile = (y: number) => {
  if (boxRef.value) {
    boxRef.value.scrollTop = y;
  }
};

const handlerToSwitchStatus = (status:string, id: string) => { 
  if(status === 'unRead') {
    // 通过id快速找到item
    const item = emailList.value.find((item: any) => item.id === id);
    if(item) {
      item.isSeen = false;
      // emailConRef.value.handlerToSwitchStatus();
    }
  }
};

watch(
  () => emailList.value,
  (newVal) => {
    // console.log("邮箱列表有变化啦有变化啦")
    // console.log(newVal)
    if(newVal && newVal.length) {
      const isNotSeen = newVal.find((item: any) => !item.isSeen);
      // console.log(isNotSeen)
      if(!isNotSeen) {
        // console.log(111)
        emit('getDetailFinished', newVal[0].topMessageId)
      }
    }
  },
  { 
    immediate: true,
    deep: true
  },
)

watch(
	() => currentId.value,
	(val) => {
    detail.value = null;
    otherEmail.value = [];
    emailList.value = [];
    if(val) {
      pagination.value.pageNum = 1;
      getEmailDetail();
    }
	},
  { immediate: true }
);

defineExpose({setUserBG, handlerToSwitchStatus})
</script>

<style lang="scss" scoped>
.box {
  flex: 1;
  height: 100%;
  padding: 0 0 10px 10px;
  background-color: #F5F6F7;
  display: flex;
  flex-direction: column;
  width: calc(100vw - 550px);

  &.center {
    align-items: center;
    justify-content: center;
  }

  .scroll_view {
    overflow: auto;
  }

  .title {
    font-weight: bold;
    color: #3f464d;
    line-height: 38px;
    padding-right: 20px;
  }

  .empty {
    background: url('/@/assets/emptybg.svg');
    height: 360px;
    width: 360px;
    background-size: cover;
  }
}
.page {
  display: flex;
  justify-content: center;
  padding: 5px 0;
}
</style>
